/*
 * Unit.cpp
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "Unit.h"
#include "Images.h"
#include "Missile.h"

Unit::Unit(SDL_Surface* img, const SDL_Rect& area)
    : Sprite(img),
      _state(NORMAL),
      _area(area),
      _max_missiles_count(1),
      _fire_delay_counter(10)
{
    reload_weapon();
    _fire_delay_counter.stop();
}

bool Unit::fire()
{
    if (!_fire_delay_counter.hit())
        return false;

    SpriteGroup<Missile>::iterator i;
    for (i = _missiles.begin(); i != _missiles.end(); ++i)
    {
        if ((*i)->is_ready())
        {
            (*i)->fire();
            _fire_delay_counter.restart();
            return true;
        }
    }

    return false;
}

bool Unit::update(void*)
{
    if (_state == EXPLODING)
        return false;

    _fire_delay_counter.tick();
   
    _missiles.update(); 
    reload_weapon();
    return true;
}

void Unit::blit(SDL_Surface* screen)
{
    _missiles.blit(screen);
    Sprite::blit(screen);
}

void Unit::erase(SDL_Surface* screen, SDL_Surface* background)
{
    _missiles.erase(screen, background);
    Sprite::erase(screen, background);
}

void Unit::reload_weapon()
{
    int missiles_to_add = _max_missiles_count - _missiles.size();

    for (int i = 0; i < missiles_to_add; ++i)
    {
        _missiles.push_back(createNewMissile());
    }
}

